package com.xkstream.client.ui;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.netease.nimlib.sdk.AbortableFuture;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.auth.AuthService;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.xkstream.client.R;
import com.xkstream.client.application.Application;
import com.xkstream.client.appmanager.AppManager;
import com.xkstream.client.base.BaseActivity;
import com.xkstream.client.entity.User;
import com.xkstream.client.presenter.UserContract;
import com.xkstream.client.presenter.UserPresenter;
import com.xkstream.client.service.DownloadService;
import com.xkstream.client.ui.live.StartLiveActivity;
import com.xkstream.client.utils.MD5Util;
import com.xkstream.client.utils.PreferenceUtils;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by admin on 2017/3/14.
 */
@Deprecated
public class LoginActivity extends BaseActivity<UserContract.Presenter> implements UserContract.View, View.OnClickListener {
    @BindView(R.id.edtAccount)
    EditText edtAccount;
    @BindView(R.id.edtPassword)
    EditText edtPassword;
    @BindView(R.id.btnLogin)
    Button btnLogin;
    @BindView(R.id.rlToolBar)
    RelativeLayout rlToolBar;
    @BindView(R.id.ivClose)
    ImageView ivClose;

    private final String USERNAME = "username";

    private final String PASSWORD = "password";
    private String userName;
    private String password;

    private Context context;

    private AlertDialog updateDialog;

    @Override
    protected void initViews(Bundle savedInstanceState) {
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA}, 2);
        }

        setUserNameAndPasswordPreference();
        context = this;
        //    createUpdateDialog();
        presenter = new UserPresenter(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @OnClick({R.id.btnLogin, R.id.ivClose, R.id.tvForgetPwd, R.id.tvSignUp})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnLogin:
//                Intent intent = new Intent();
//                intent.setClass(LoginActivity.this, MainActivity.class);
//                startActivity(intent);
                userLogin();
                break;
            case R.id.tvCancel:
                updateDialog.dismiss();
                break;
            case R.id.tvSure:
                serviceStart("http://180.153.105.146/imtt.dd.qq.com/16891/1CF13852ED7B4AEE8623FBCFD2440ACE.apk?mkey=58f59807c7ddc68f&f=b208&c=0&fsname=com.miqtech.master.client_4.1.04_401004.apk&csr=1bbd&p=.apk");
                updateDialog.dismiss();
                break;
            case R.id.ivClose:
                sureCloseDialog();
                break;
            case R.id.tvForgetPwd:

                break;
            case R.id.tvSignUp:
                startActivityRigster();
                break;
        }
    }

    private void sureCloseDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setMessage("确认退出吗？");
        builder.setTitle("提示");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                AppManager.getAppManager().AppExit(context);

            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });

        builder.create().show();
    }

    private void startActivityForgetPwd() {
        Intent intent = new Intent();
    }

    private void startActivityRigster() {
        Intent intent = new Intent();
        intent.setClass(context, RegisterActivity.class);
        startActivity(intent);
    }

    private void userLogin() {
        userName = edtAccount.getText().toString();
        password = edtPassword.getText().toString();
        if (TextUtils.isEmpty(userName)) {
            showToast(R.string.hint_input_username);
            return;
        } else if (TextUtils.isEmpty(password)) {
            showToast(R.string.hint_input_password);
            return;
        }
        String newPassword = MD5Util.string2MD5(password);
        Map<String, Object> params = new HashMap<>();
        params.put("user_name", userName);
        params.put("password", newPassword);
        //     params.put("logintype", 0 + "");
        presenter.userLogin(params);

    }

    /**
     * 设置输入框默认账号密码
     */
    private void setUserNameAndPasswordPreference() {
        String userName = PreferenceUtils.getString(USERNAME);
        String password = PreferenceUtils.getString(PASSWORD);
        if (!TextUtils.isEmpty(userName)) {
            edtAccount.setText(userName);
            edtAccount.setSelection(userName.length());
        }
        if (!TextUtils.isEmpty(password)) {
            edtPassword.setText(password);
            edtPassword.setSelection(password.length());
        }
    }

    private void createUpdateDialog() {
        updateDialog = new AlertDialog.Builder(context).create();
        updateDialog.show();
        updateDialog.setCancelable(false);
        updateDialog.setCanceledOnTouchOutside(false);
        Window window = updateDialog.getWindow();
        WindowManager.LayoutParams lp =
                updateDialog.getWindow().getAttributes();
        window.setContentView(R.layout.layout_selectoralert_dialog);
        lp.width = (int) (Application.WIDTH - getResources().getDimension(R.dimen.activity_horizontal_margin) * 2);
        lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);
        TextView tvContent = (TextView) updateDialog.findViewById(R.id.tvContent);
        TextView tvCancel = (TextView) updateDialog.findViewById(R.id.tvCancel);
        TextView tvSure = (TextView) updateDialog.findViewById(R.id.tvSure);
        tvContent.setText(getResources().getString(R.string.sure_download));
        tvSure.setText(getResources().getString(R.string.sure));
        tvCancel.setText(getResources().getString(R.string.cancel));
        tvCancel.setOnClickListener(this);
        tvSure.setOnClickListener(this);
    }

    private void serviceStart(String url) {
        Intent it = new Intent(LoginActivity.this, DownloadService.class);
        Bundle bundle = new Bundle();

        //it.putExtra("apkUrl", version.getUrl());
        bundle.putString("apkUrl", url);
        //it.putExtra("type", type);
        it.putExtras(bundle);
        startService(it);
    }

    @Override
    public void onBackPressed() {
        //super.onBackPressed();
        sureCloseDialog();
    }

    @Override
    public void setPresenter(UserContract.Presenter presenter) {
        this.presenter = presenter;
    }

    @Override
    public void loginSuccess(User user) {
        PreferenceUtils.putString(USERNAME, userName);
        PreferenceUtils.putString(PASSWORD, password);

        // 必须设置用户信息，建议在initSDK之前设置
        Application.mZegoLiveRoom.setUser(user.getUser_code(), userName);
        Intent intent = new Intent();
        intent.setClass(LoginActivity.this, StartLiveActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void loginFailed(int code, String msg) {
        showToast(R.string.wrong_account_or_passowrd);
    }

    @Override
    public void showError(String message) {
        showToast(message);
    }
}
